<?php
namespace App\Libs\wrapper;
use Illuminate\Support\Facades\DB;
class Product extends Comm{
////////////////////////////////////////////////  产品

////////////////////// wish
	/*
	 * 获取商品信息
	 * @param shop_id 店铺id
	 * @param mark 授权类型:1.wish，2.vova，3.lazada
	 * @param page 页码
	 * @param limit 每页条数
	 * @param time_start 开始时间
	 * @param time_end 结束时间
	 **/
	public function product_get_wish($data)
	{
		if(empty($data)){
			return '接收值为空';
		}

		//// 获取店铺信息
		$sql = "select s.*
	                from shop s
	                where s.Id={$data['shop_id']}
	                limit 1";
		$shop_find = json_decode(json_encode(db::select($sql)), true);
		if(empty($shop_find)){
			return '获取店铺数据失败';
		}else if(empty($shop_find[0]['app_data'])){
			return '授权数据为空';
		}

		//// 实例化 wish 类
		$arr = json_decode($shop_find[0]['app_data'], true);
		$arr['access_token'] = $shop_find[0]['access_token'];
		$arr['shop_id'] = $shop_find[0]['Id'];
		$call_wish = new \App\Libs\platformApi\Wish($arr);

		//// 获取商品
		$arr = $data;
		$product_get = $call_wish->product_get($arr);
//		return $product_get;
		if ($product_get['code'] != 0) {
			return $product_get;
		}

		//// 存储数据
		$time = date('Y-m-d H:i:s', time());
		if(!empty($product_get['data'])){
			foreach ($product_get['data'] as $k=>$v){
				//// 查询是否存在
				$sql = "select 	`Id`
	        	            from `product`
	        	            where shop_id={$data['shop_id']} and product_id_pt='{$v['Product']['id']}'
	        	            limit 1";
				$product_find = json_decode(json_encode(db::select($sql)), true);


				//// 已否已删除
				if($v['Product']['removed_by_merchant'] == 'True'){
					// 修改
					$sql = "update `product`
				                set `is_delete`=1
				                where `Id` = {$product_find[0]['Id']}";
					db::update($sql);
					continue;
				}

				$product_name = str_replace("'", "\'", $v['Product']['name']);// 产品名称
				$product_description = str_replace("'", "\'", $v['Product']['description']);// 产品描述
				$parent_sku = str_replace("'", "\'", $v['Product']['parent_sku']);// 父sku
				// 最后更新时间
				$last_time01 = explode("T", $v['Product']['last_updated']);
				$last_time02 = explode("-", $last_time01[0]);
				$last_time = $last_time02[2].'-'.$last_time02[0].'-'.$last_time02[1].' '.$last_time01[1];
				// 上传平台时间
				$add_time01 = explode("-", $v['Product']['date_uploaded']);
				$add_time = $add_time01[2].'-'.$add_time01[0].'-'.$add_time01[1];

				if(empty($product_find)){
					// 没有，则新增

					$arr = array();
					$arr['platform_id'] = $shop_find[0]['platform_id'];
					$arr['shop_id'] = $shop_find[0]['Id'];
					$arr['product_id_pt'] = $v['Product']['id'];
					$arr['product_name'] = $product_name;
					$arr['product_description'] = $product_description;
					$arr['parent_sku'] = $parent_sku;
					$arr['main_image'] = $v['Product']['main_image'];
					$arr['last_update_time'] = $last_time;
					$arr['add_time'] = $add_time;
					$arr['create_time'] = $time;
					$product_add = db::table('product')->insertGetId($arr);
					if(!$product_add){
						continue;
					}
					$product_id = $product_add;
				}else{
					// 修改
					$sql = "update `product`
				                set `product_name`='{$product_name}', `product_description`='{$product_description}', `parent_sku`='{$parent_sku}', `main_image`='{$v['Product']['main_image']}', `last_update_time`='{$last_time}'
				                where `Id` = {$product_find[0]['Id']}";
					$product_update = db::update($sql);
					$product_id = $product_find[0]['Id'];
				}

				//// sku
				foreach ($v['Product']['variants'] as $k1=>$v1){
					$Variant = $v1['Variant'];

					$Variant['sku'] = str_replace("'", "\'", $Variant['sku']);// 产品名称
					//// 是否存在
					$sql = "select `Id`
			                    from product_sku
			                    where product_id={$product_id} and goods_sku='{$Variant['sku']}'
			                    limit 1";
					$sku_find = json_decode(json_encode(db::select($sql)), true);

					//// 处理数据
					// 尺码
					$size = !empty($Variant['size']) ? $Variant['size'] : '';
					// 颜色
					$color = !empty($Variant['color']) ? $Variant['color'] : '';
					// 价格
					$price = $Variant['price'] * 100;
					// 运费
					$shipping_fee = (empty($Variant['shipping'])? 0 : $Variant['shipping']) * 100;
					// 启用状态
					$enabled = $Variant['enabled'] ? 2 : 1;
					// 主图
					$main_image = !empty($Variant['main_image']) ? $Variant['main_image'] : '';
					// 所有图片
					$all_images = str_replace("|", ",", $Variant['all_images']);

					if(empty($sku_find)) {
						// 没有，则新增
						$sql = "insert into product_sku(`product_id`, `goods_sku`, `price`, `storage`, `shipping_fee`, `main_image`, `all_images`, `size`, `color`, `is_enabled`)
									values ({$product_id}, '{$Variant['sku']}', {$price}, {$Variant['inventory']}, {$shipping_fee}, '{$main_image}', '{$all_images}', '{$size}', '{$color}', {$enabled})";
						db::insert($sql);
					}else{
						// 有，则修改

						$sql = "update product_sku
				                    set `goods_sku`='{$Variant['sku']}',`price`={$price}, `storage`={$Variant['inventory']}, `shipping_fee`={$shipping_fee},`main_image`='{$main_image}', `all_images`='{$all_images}', `size`='{$size}', `color`='{$color}', `is_enabled`={$enabled}
				                    where `Id`={$sku_find[0]['Id']}";
						$sku_update = db::update($sql);
					}
				}
			}
		}


		// 判断是不是最后一页
		if(count($product_get['data']) == $data['limit']){
			return 2;
		}

		// 修改定时器起始时间
		$timer_time = date('Y-m-d H:i:s');
		$time_start_d = date('Y-m-d', strtotime($data['time_start']));
		$time_d = date('Y-m-d', time());
		if($time_start_d < $time_d){
			$time_add_day = date('Y-m-d H:i:s', strtotime($data['time_start']) + 3600*24);
			if($time_add_day >= $timer_time){
				$timer_time = $time_d;
			}else{
				$timer_time = $time_add_day;
			}
		}
		$sql = "update `shop`
		                set `timer_time`='{$timer_time}'
		                where `Id` = {$data['shop_id']}";
		db::update($sql);

		/*// 删除记录
		if(!empty($data['mq_id'])){
			// redis
			$redis = new \Redis();
			$redis->connect("127.0.0.1", 6379);
			$redis->del($data['mq_id']);
		}*/

		return 1;
	}


////////////////////// vova
	/*
	 * 获取商品信息
	 * @param shop_id 店铺id
	 * @param mark 授权类型:1.wish，2.vova，3.lazada
	 * @param page 页码
	 * @param limit 每页条数
	 * @param time_start 开始时间
	 * @param time_end 结束时间
	 **/
	public function product_get_vova($data)
	{
		if(empty($data)){
			return '接收值为空';
		}

		//// 获取店铺信息
		$sql = "select s.*
	                from shop s
	                where s.Id={$data['shop_id']}
	                limit 1";
		$shop_find = json_decode(json_encode(db::select($sql)), true);
		if(empty($shop_find)){
			return '获取店铺数据失败';
		}else if(empty($shop_find[0]['access_token'])){
			return 'access_token为空';
		}

		//// 实例化 vova 类
		$arr = array(
			'access_token' => $shop_find[0]['access_token']
		);
		$call_vova = new \App\Libs\platformApi\Vova($arr);
//		return $data;
		//// 获取商品
		$arr = array();
		$arr['last_update_time_start'] = $data['time_start'];
		$arr['last_update_time_end'] = $data['time_end'];
		$arr['page_arr_perPage'] = $data['limit'];
		$arr['page_arr_page'] = $data['page'];
		$product_get = $call_vova->product_get($arr);
//		return $product_get;
		if(!is_array($product_get)){
			return $product_get;
		}

		//// 存储数据
		$time = date('Y-m-d H:i:s', time());
		if(!empty($product_get['product_list'])){

			foreach ($product_get['product_list'] as $k=>$v){
				//// 查询是否存在
				$sql = "select 	`Id`
	        	            from `product`
	        	            where shop_id={$data['shop_id']} and product_id_pt='{$v['product_id']}'
	        	            limit 1";
				$product_find = json_decode(json_encode(db::select($sql)), true);

				//// 已否已删除
				if($v['is_delete'] == 1){
					// 修改
					$sql = "update `product`
				                set `is_delete`={$v['is_delete']}
				                where `Id` = {$product_find[0]['Id']}";
					db::update($sql);
					continue;
				}

				$product_name = str_replace("'", "\'", $v['goods_name']);// 产品名称
				$product_description = str_replace("'", "\'", $v['goods_description']);// 描述
				$parent_sku = str_replace("'", "\'", $v['parent_sku']);// 父sku

				$last_time = date('Y-m-d H:i:s', strtotime($v['last_update_time']) + 3600*8);// 最后更新时间
				$add_time = date('Y-m-d H:i:s', strtotime($v['add_time']) + 3600*8);// 上传平台时间
				if(empty($product_find)){
					// 没有，则新增

					$arr = array();
					$arr['platform_id'] = $shop_find[0]['platform_id'];
					$arr['shop_id'] = $shop_find[0]['Id'];
					$arr['product_id_pt'] = $v['product_id'];
					$arr['cat_id'] = $v['cat_id'];
					$arr['product_name'] = $product_name;
					$arr['product_description'] = $product_description;
					$arr['parent_sku'] = $parent_sku;
					$arr['main_image'] = $v['main_image'];
					$arr['last_update_time'] = $last_time;
					$arr['add_time'] = $add_time;
					$arr['goods_promotion'] = $v['goods_promotion'];
					$arr['ban_status'] = $v['ban_status'];
					$arr['wait_for_check'] = $v['wait_for_check'];
					$arr['is_on_sale'] = $v['is_on_sale'];
					$arr['create_time'] = $time;

					$product_add = db::table('product')->insertGetId($arr);
					if(!$product_add){
						continue;
					}
					$product_id = $product_add;
				}else{
					// 修改
					$sql = "update `product`
				                set `product_name`='{$product_name}', `product_description`='{$product_description}', `parent_sku`='{$parent_sku}', `main_image`='{$v['main_image']}', `cat_id`='{$v['cat_id']}', `last_update_time`='{$last_time}', `add_time`='{$v['add_time']}', `goods_promotion`={$v['goods_promotion']}, `is_on_sale`={$v['is_on_sale']}, `ban_status`={$v['ban_status']}, `wait_for_check`={$v['wait_for_check']}
				                where `Id` = {$product_find[0]['Id']}";
					db::update($sql);
					$product_id = $product_find[0]['Id'];
				}

				//// sku
				foreach ($v['sku_list'] as $k1=>$v1){
					//// 是否存在
					$goods_sku = str_replace("'", "\'", $v1['goods_sku']);// sku
					$sql = "select `Id`
			                    from product_sku
			                    where product_id={$product_id} and goods_sku='{$goods_sku}'
			                    limit 1";
					$sku_find = json_decode(json_encode(db::select($sql)), true);

					//// 处理数据
					$style_info = json_decode($v1['style_info'], true);
					// 尺码
					$size = !empty($style_info['size']) ? str_replace("'", "\'", $style_info['size']) : '';
					// 颜色
					$color = !empty($style_info['color']) ? str_replace("'", "\'", $style_info['color']) : '';
					// 价格
					$price = $v1['shop_price'] * 100;
					// 运费
					$shipping_fee = $v1['shipping_fee'] * 100;

					if(empty($sku_find)) {
						// 没有，则新增

						$sql = "insert into product_sku(`product_id`, `goods_sku`, `price`, `storage`, `shipping_fee`, `size`, `color`)
									values ({$product_id}, '{$goods_sku}', {$price}, {$v1['storage']}, '{$shipping_fee}', '{$size}', '{$color}')";
						db::insert($sql);
					}else{
						// 有，则修改

						$sql = "update product_sku
				                    set `goods_sku`='{$goods_sku}',`price`={$price}, `storage`={$v1['storage']}, `shipping_fee`={$shipping_fee}, `size`='{$size}', `color`='{$color}'
				                    where `Id` = {$sku_find[0]['Id']}";
						db::update($sql);
					}

				}
			}
		}

		// 判断是不是最后一页
		if($product_get['page_arr']['page'] < $product_get['page_arr']['totalPage']){
			return 2;
		}

		// 修改定时器起始时间
		$timer_time = date('Y-m-d H:i:s');
		$time_start_d = date('Y-m-d', strtotime($data['time_start']));
		$time_d = date('Y-m-d', time());
		if($time_start_d < $time_d){
			$time_add_day = date('Y-m-d H:i:s', strtotime($data['time_start']) + 3600*24);
			if($time_add_day >= $timer_time){
				$timer_time = $time_d;
			}else{
				$timer_time = $time_add_day;
			}
		}
		$sql = "update `shop`
		                set `timer_time`='{$timer_time}'
		                where `Id` = {$data['shop_id']}";
		db::update($sql);

		// 删除记录
		/*if(!empty($data['mq_id'])){
			// redis
			$redis = new \Redis();
			$redis->connect("127.0.0.1", 6379);
			$redis->del($data['mq_id']);
		}*/

		return 1;
	}

////////////////////// lazada
	/*
	 * 获取商品信息
	 * @param shop_id 店铺id
	 * @param mark 授权类型:1.wish，2.vova，3.lazada
	 * @param page 页码
	 * @param limit 每页条数
	 * @param time_start 开始时间
	 * @param time_end 结束时间
	 **/
	public function product_get_lazada($data)
	{
		if(empty($data)){
			return '接收值为空';
		}

		//// 获取店铺信息
		$sql = "select s.*
	                from shop s
	                where s.Id={$data['shop_id']}
	                limit 1";
		$shop_find = json_decode(json_encode(db::select($sql)), true);
		if(empty($shop_find)){
			return '获取店铺数据失败';
		}else if(empty($shop_find[0]['app_data'])){
			return '授权数据为空';
		}

		//// 实例化 lazada 类
		$arr = json_decode($shop_find[0]['app_data'], true);
		$arr['access_token'] = $shop_find[0]['access_token'];
		$arr['shop_id'] = $shop_find[0]['Id'];
		$call_lazada = new \App\Libs\platformApi\Lazada($arr);

		//// 获取商品
		$arr = $data;
		$product_get = $call_lazada->product_get($arr);
		if ($product_get['code'] != 0) {
			return $product_get;
		}

		//// 存储数据
		$time = date('Y-m-d H:i:s', time());
		if(!empty($product_get['data'])){

			foreach ($product_get['data']['products'] as $k=>$v){
				//// 查询是否存在
				$sql = "select 	`Id`
	        	            from `product`
	        	            where shop_id={$data['shop_id']} and product_id_pt='{$v['item_id']}'
	        	            limit 1";
				$product_find = json_decode(json_encode(db::select($sql)), true);

				//// 处理数据
				// 商品名称
				$product_name = str_replace("'", "\'", $v['attributes']['name']);
				// 描述
				$product_description = !empty($v['attributes']['short_description']) ? str_replace("'", "\'", $v['attributes']['short_description']) : '';
				// 主图
				$main_image = !empty($v['skus'][0]['Images'][0]) ? $v['skus'][0]['Images'][0] : '';
				// 最后更新时间  转 中国时间
				$last_time = $call_lazada->time_hm($v['updated_time']);
				$last_time = date('Y-m-d H:i:s', (strtotime($last_time) + 3600*8));
				// 上传平台时间  转 中国时间
				$add_time = $call_lazada->time_hm($v['created_time']);
				$add_time = date('Y-m-d H:i:s', (strtotime($add_time) + 3600*8));

				if(empty($product_find)){
					// 没有，则新增

					$arr = array();
					$arr['platform_id'] = $shop_find[0]['platform_id'];
					$arr['shop_id'] = $shop_find[0]['Id'];
					$arr['product_id_pt'] = $v['item_id'];
					$arr['cat_id'] = $v['primary_category'];
					$arr['product_name'] = $product_name;
					$arr['product_description'] = $product_description;
//					$arr['parent_sku'] = $v['skus'][0]['SellerSku'];
					$arr['parent_sku'] = $v['item_id'];
					$arr['main_image'] = $main_image;
					$arr['last_update_time'] = $last_time;
					$arr['add_time'] = $add_time;
					$arr['create_time'] = $time;
					$product_add = db::table('product')->insertGetId($arr);
					if(!$product_add){
						continue;
					}
					$product_id = $product_add;
				}else{
					// 修改
					$sql = "update `product`
				                set `product_name`='{$product_name}', `product_description`='{$product_description}',
				                `parent_sku`='{$v['item_id']}', `main_image`='{$main_image}', `last_update_time`='{$last_time}'
				                where `Id` = {$product_find[0]['Id']}";
					db::update($sql);
					$product_id = $product_find[0]['Id'];
				}

				//// sku
				foreach ($v['skus'] as $k1=>$v1){
					//// 是否存在
					$v1['ShopSku'] = str_replace("'", "\'", $v1['ShopSku']);
					$sql = "select `Id`
			                    from product_sku
			                    where product_id={$product_id} and goods_sku='{$v1['ShopSku']}'
			                    limit 1";
					$sku_find = json_decode(json_encode(db::select($sql)), true);

					// 尺码
					$size = !empty($v1['size']) ? $v1['size'] : '';
					// 颜色
					$color = !empty($v1['color_family']) ? $v1['color_family'] : '';
					// 主图
					$main_image = !empty($v1['Images'][0]) ? $v1['Images'][0] : '';;
					// 所有图片
					$all_images = implode(',', $v1['Images']);
					// 价格
					$price = $v1['price'] * 100;

					if(empty($sku_find)) {
						// 没有，则新增

						$sql = "insert into product_sku(`product_id`, `goods_sku`, `price`, `storage`, `main_image`, `all_images`, `size`, `color`, `state`)
									values ({$product_id}, '{$v1['ShopSku']}', {$price}, {$v1['quantity']}, '{$main_image}', '{$all_images}', '{$size}', '{$color}', '{$v1['Status']}')";
						db::insert($sql);
					}else{
						// 有，则修改

						$sql = "update product_sku
				                    set `goods_sku`='{$v1['ShopSku']}', `price`={$price}, `storage`={$v1['quantity']}, `main_image`='{$main_image}', `all_images`='{$all_images}', `size`='{$size}', `color`='{$color}', `state`='{$v1['Status']}'
				                    where `Id` = {$sku_find[0]['Id']}";
						db::update($sql);
					}

				}
			}
		}

		// 判断是不是最后一页
		if(!empty($product_get['data']['products'])){
			if(count($product_get['data']['products']) == $data['limit']){
				return 2;
			}
		}

		// 修改定时器起始时间
		$timer_time = date('Y-m-d H:i:s');
		$time_start_d = date('Y-m-d', strtotime($data['time_start']));
		$time_d = date('Y-m-d', time());
		if($time_start_d < $time_d){
			$time_add_day = date('Y-m-d H:i:s', strtotime($data['time_start']) + 3600*24);
			if($time_add_day >= $timer_time){
				$timer_time = $time_d;
			}else{
				$timer_time = $time_add_day;
			}
		}
		$sql = "update `shop`
		                set `timer_time`='{$timer_time}'
		                where `Id` = {$data['shop_id']}";
		db::update($sql);

		// 删除记录
		/*if(!empty($data['mq_id'])){
			// redis
			$redis = new \Redis();
			$redis->connect("127.0.0.1", 6379);
			$redis->del($data['mq_id']);
		}*/

		return 1;
	}

//	public function barcode_export($data){
//        $where = "1=1";
//
//        if (!empty($data['asin'])) {
//            $asinString = '';
//            $asinData = explode(',',$data['asin']);
//            foreach($asinData as $asinKey => $asinVal){
//                $asinStr  = "'".$asinVal."',";
//                $asinString .= $asinStr;
//            }
//            $newAsin = substr($asinString,0,strlen($asinString)-1);
//            // sku_ids sku id
//            $where .= " and p.asin in ({$newAsin})";
//        } else {
//            if (!empty($data['platform_id'])) {
//                //     $where .= " and p.platform_id = {$params['platform_id']}";
//                $where .= " and p.platform_id = {$data['platform_id']}";
//            }
//            if (!empty($data['shop_id'])) {
//                $where .= " and p.shop_id = {$data['shop_id']}";
//            }
//            if (!empty($data['product_sku'])) {
//                $where .= " and p.sellersku like '%{$data['product_sku']}%'";
//            }
//            if (!empty($data['product_fnsku'])) {
//                $where .= " and p.fnsku like '%{$data['product_fnsku']}%'";
//            }
//            if (!empty($data['product_asin'])) {
//                $where .= " and p.asin like '%{$data['product_asin']}%'";
//            }
//            if (!empty($data['product_key'])) {
//                $product_key=$data['product_key'];
//                $keySql = "select sku
//                from saihe_product
//                where product_name_cn like '%{$product_key}%'
//                ";
//                $key = json_decode(json_encode(DB::select($keySql)), true);
//                $skulist=array();
//                foreach ($key as $v){
//                    $skulist[]="'".trim($v['sku'])."'";
//                }
//                if(isset($skulist)) $saihesku=implode(",",$skulist);
//
//                $where .= " and spd.saihe_sku in ({$saihesku})";
//            }
//
//            if (!empty($data['order_source_sku'])) {
//                //库存sku搜索
//                $order_source_sku=explode(",",$data['order_source_sku']);
//                $str = '';
//                foreach ($order_source_sku as $k=>$v){
//                    $str .= " spd.order_source_sku like "."'%{$v}%' or";
//
//                }
//                $newStr = substr($str,0,strlen($str)-2);
//                $where.=" and {$newStr}";
//
//            }
//            /*if (!empty($data['order_source_sku'])) {
//                $str = '';
//                $orderCourse = $data['order_source_sku'];
//                $courseSkuArr = explode(',',$orderCourse);
//                foreach ($courseSkuArr as $courseValue){
//                    $str .= "order_source_sku like "."'%{$courseValue}%' or";
//                }
//                $newstr = substr($str,0,strlen($str)-2);
////                var_dump($newstr);die;
//                $shProSql = "select id
//                from saihe_product_detail
//                where {$newstr}
//                ";
//                $shId = json_decode(json_encode(DB::select($shProSql)), true);
//                $skulist=array();
//                foreach ($shId as $v){
//                    $idList[]="'".trim($v['id'])."'";
//                }
//                if(isset($idList)) $saihesku=implode(",",$idList);
//
//                $where .= " and spd.id in ({$saihesku})";
//            }*/
//            //create_time 创建时间
//            /*if (!empty($data['create_time'])) {
//                $sel_time = explode(' - ',$data['create_time']);
//                $sel_time[1] = $sel_time[1].' 23:59:59';
//                $where .= " and e.create_time>='{$sel_time[0]}' and e.create_time<='{$sel_time[1]}'";
//            }*/
//        }
////        var_dump($where);die;
//        $sql = "select p.sellersku,p.asin,p.sellersku,spd.saihe_sku,spd.order_source_sku,ps.goods_sku,p.fnsku,spd.order_source_name
//                from product_detail p
//                join product_sku ps on p.product_sku_id = ps.Id
//                join platform pf on p.platform_id=pf.id
//                join shop s on p.shop_id = s.Id
//                join saihe_product_detail spd on p.asin = spd.asin
//                where {$where} order by p.id desc";
//        $list = json_decode(json_encode(DB::select($sql)), true);
//        foreach ($list as $key=>$value){
//            $saihe_sku = $value['saihe_sku'];
//            $saiHeSql = "select sp.small_image_url,sp.sku,sp.product_name,sp.color,sp.size,sp.brand_name
//                from saihe_product sp
//                where sp.sku = '{$saihe_sku}'
//                ";
//            $saiHe = json_decode(json_encode(DB::select($saiHeSql)), true);
//            $list[$key]['small_image_url'] = isset($saiHe[0]['small_image_url'])?"{$saiHe[0]['small_image_url']}":'';
////            $list[$key]['sku'] = isset($saiHe[0]['sku'])?"{$saiHe[0]['sku']}":'';
//            $list[$key]['product_name'] = isset($saiHe[0]['product_name'])?"{$saiHe[0]['product_name']}":'';
//            $list[$key]['color'] = isset($saiHe[0]['color'])?"{$saiHe[0]['color']}":'';
//            $list[$key]['size'] = isset($saiHe[0]['size'])?"{$saiHe[0]['size']}":'';
//            $list[$key]['brand_name'] = isset($saiHe[0]['brand_name'])?"{$saiHe[0]['brand_name']}":'';
////            $list[$key]['client_sku'] = isset($saiHe[0]['client_sku'])?"{$saiHe[0]['client_sku']}":'';
//
//        }
//
//
//        ////处理数据
//        foreach ($list as $ka => $va) {
//            //var_dump($va);die;
//            $list[$ka]['contract_no'] = '';
//            $list[$ka]['small_image_url'] = $va['small_image_url'];
//            $list[$ka]['item_number'] = '';
//            $list[$ka]['order_source_sku'] = $va['order_source_sku'];
//            $list[$ka]['sku'] = $va['goods_sku'];
//            $list[$ka]['product_name'] = $va['product_name'];
//            $list[$ka]['color_cn'] = '';
//            $list[$ka]['color_en'] = $va['color'];
//            $list[$ka]['size'] = $va['size'];
//            $list[$ka]['order_source_name'] = $va['order_source_name'];
//            $list[$ka]['style_category'] = 'NEW';
//            $list[$ka]['place'] = 'MADE IN CHINA';
//            $list[$ka]['order_count'] = '';
//            $list[$ka]['code_data'] = $va['fnsku'];
//
//
//
//        }
////		return $list;
//        $title = array(
//            'contract_no' => '订单合同号',
//            'small_image_url' => '图片',
//            'item_number' => '款号',
//            'order_source_sku' => '库存SKU',
//            'sku' => 'SKU',
//            'product_name' => '英文品名描述',
//            'color_cn' => '颜色',
//            'color_en' => '颜色（英文）',
//            'size' => '尺码',
//            'order_source_name' => '品牌logo',
//            'style_category' => '款示类别',
//            'place' => '制造地',
//            'order_count' => '合计下单数量',
//            'code_data' => '条码资料',
//        );
////        echo "<pre>";
////var_dump($list);die;
//        error_reporting(E_ALL);
//        date_default_timezone_set('PRC');
//        $objPHPExcel = new \PHPExcel();
//        $PHPExcel_Style_Alignment = new \PHPExcel_Style_Alignment;
//
//        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
//        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
//        // 设置excel标题
//
//        // 设置excel标题
//        $index = 0;
//        foreach ($title as $k => $v) {
//            $objPHPExcel->getActiveSheet()->getStyle('A1:AA1')->getFont()->setBold(true);//第一行是否加粗
//            $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(25);    //第一行行高
//            $objPHPExcel->getActiveSheet()->setCellValue($cellName[$index] . "1", $v);
//            $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(60);
//            $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(11);
//            //设置水平居中
//            $objPHPExcel->getActiveSheet()
//                ->getStyle('A1:AA1')
//                ->getAlignment()
//                ->setHorizontal($PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//            //设置垂直居中
//            $objPHPExcel->getActiveSheet()
//                ->getStyle('A1:AA1')
//                ->getAlignment()
//                ->setVertical($PHPExcel_Style_Alignment::VERTICAL_CENTER);
//            //自动换行
//            $objPHPExcel->getActiveSheet()
//                ->getStyle('A1:AA1')
//                ->getAlignment()
//                ->setWrapText(true);
//
//            $index++;
//        }
//
//        //判断文件夹是否已存在
//        $wenjian = 'assess/Qiniu';
//        if (!is_dir($wenjian)) {
//            mkdir($wenjian, 0777, true);
//        }
//        // 填充excel数据 与标题一一对应
//        $img_del = array();//需删除的图片
//        foreach ($list as $k => $v) {
//            $num = $k + 2;
//            //字体大小
//            $objPHPExcel->getActiveSheet()
//                ->getStyle('A' . $num . ':' . 'AA' . $num)
//                ->getFont()
//                ->setSize(10);
//            //设置水平居中
//            $objPHPExcel->getActiveSheet()
//                ->getStyle('A' . $num . ':' . 'AA' . $num)
//                ->getAlignment()
//                ->setHorizontal($PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//            //设置垂直居中
//            $objPHPExcel->getActiveSheet()
//                ->getStyle('A' . $num . ':' . 'AA' . $num)
//                ->getAlignment()
//                ->setVertical($PHPExcel_Style_Alignment::VERTICAL_CENTER);
//            //自动换行
//            $objPHPExcel->getActiveSheet()
//                ->getStyle('A' . $num . ':' . 'AA' . $num)
//                ->getAlignment()
//                ->setWrapText(true);
//
//            // 重置列索引起始位
//            $i = 0;
//            foreach ($title as $key => $value) {
//                if ($key=='small_image_url' && $v[$key]!='') {
//                    $preg = "/^http(s)?:\\/\\/.+/";
//                    if(!(preg_match($preg, $v[$key]))){
//                        $objPHPExcel->setActiveSheetIndex(0)//Excel的第A列，uid是你查出数组的键值，下面以此类推
//                        ->setCellValue($cellName[$i] . $num, '无');
//                        $i++;
//                        continue;//跳出循环
//                    }
//                    ////七牛云图片下载到本地
//                    $url = $v[$key];
//                    $aa = get_headers($url);//检验url是否能访问
//                    if($aa[0] != 'HTTP/1.1 200 OK'){
//                        $objPHPExcel->setActiveSheetIndex(0)//Excel的第A列，uid是你查出数组的键值，下面以此类推
//                        ->setCellValue($cellName[$i] . $num, '无');
//                        $i++;
//                        continue;//跳出循环
//                    }
//
//                    ob_start();  //打开缓冲区
//                    readfile($url);  //该函数读入一个文件并写入到输出缓冲
//                    $img  = ob_get_contents();  //返回内部缓冲区的内容
//                    ob_end_clean();  //删除内部缓冲区的内容，并且关闭内部缓冲区,这个函数不会输出内部缓冲区的内容而是把它删除
//                    $size = strlen($img);	//函数返回字符串的长度
//                    $filename = time().'_'.(rand(100,999)*rand(1,999));
//                    $file_n =  $_SERVER['DOCUMENT_ROOT'] .'/assess/Qiniu/'.$filename.'.jpg';
//                    $fp = fopen($file_n, 'w+');//打开文件 一定要添相对路径
//                    fwrite($fp, $img); //写入信息到
//                    fclose($fp);//关闭文件
//
//                    $img_del[] = $file_n;//用于删除文件
//
//                    //// 图片插入到Excel
//                    //获取图片
//                    $objDrawing = new \PHPExcel_Worksheet_Drawing();
//                    $objDrawing->setPath($file_n);//图片路径
//                    // 设置图片宽度高度
//                    $objDrawing->setResizeProportional(false);
//                    $objDrawing->setHeight(60);//照片高度
//                    $objDrawing->setWidth(60); //照片宽度
//                    //设置图片要插入的单元格
//                    $objDrawing->setOffsetX(10);
//                    $objDrawing->setOffsetY(10);
//                    $objDrawing->setCoordinates($cellName[$i] . $num);
//                    $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
//                    $i++;
//                } else {
//                    $objPHPExcel->setActiveSheetIndex(0)//Excel的第A列，uid是你查出数组的键值，下面以此类推
//                    ->setCellValue($cellName[$i] . $num, $v[$key]);
//                    $i++;
//                }
//            }
//        }
//
//
//        $objPHPExcel->getActiveSheet()->setTitle('work');
//        $objPHPExcel->setActiveSheetIndex(0);
//        header('Content-Type: application/vnd.ms-excel');
//        header('Content-Disposition:attachment;filename="条码列表.xls"');
//        header('Cache-Control: max-age=1');
//        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
//        $objWriter->save('php://output');
//        //删除下载的图片
//
//        if(!empty($img_del)){
//            foreach ($img_del as $val){
//                unlink($val);
//            }
//        }
//
//        exit();
//    }

public function barcode_export_ck($data){
// 	$where = "1=1";
	if (!empty($data['id'])) {
		$idData = explode(',',$data['id']);
		$query['ids'] = $idData;
		$product_model = new  \App\Models\ProductModel();
		$lists = $product_model->getBarcodeByCk($query);
	}else{
		return "请传id";
	}
// 	$url_type = $data['url_type']??'custom_sku';
// 	if (!empty($data['id'])) {
// 		$idString = '';
// 		$idData = explode(',',$data['id']);
// 		foreach($idData as $idVal){
// 			$idStr  = "'".$idVal."',";
// 			$idString .= $idStr;
// 		}
// 		$newId = substr($idString,0,strlen($idString)-1);
// 		// sku_ids sku id
// 		$where .= " and p.id in ({$newId}) order by field(p.id,{$newId})";
// 	} else {
// 		if (!empty($data['platform_id'])) {
// 			//     $where .= " and p.platform_id = {$params['platform_id']}";
// 			$where .= " and p.platform_id = {$data['platform_id']}";
// 		}
// 		if (!empty($data['shop_id'])) {
// 			$where .= " and p.shop_id = {$data['shop_id']}";
// 		}
// 		if (!empty($data['product_sku'])) {
// 			$where .= " and p.sellersku like '%{$data['product_sku']}%'";
// 		}
// 		if(!empty($data['sellersku_arr'])){
// 			$where .= " and p.sellersku in ({$data['sellersku_arr']}) order by field(p.sellersku,{$data['sellersku_arr']})";
// 		}
// 		if (!empty($data['product_fnsku'])) {
// 			$where .= " and p.fnsku like '%{$data['product_fnsku']}%'";
// 		}
// 		if (!empty($data['product_asin'])) {
// 			$where .= " and p.asin like '%{$data['product_asin']}%'";
// 		}
// 		if (!empty($data['product_key'])) {
// 			$product_key=$data['product_key'];
// 			$keySql = "select sku
// 			from saihe_product
// 			where product_name_cn like '%{$product_key}%'
// 			";
// 			$key = json_decode(json_encode(DB::select($keySql)), true);
// 			$skulist=array();
// 			foreach ($key as $v){
// 				$skulist[]="'".trim($v['sku'])."'";
// 			}
// 			if(isset($skulist)) $saihesku=implode(",",$skulist);

// 			$where .= " and spd.saihe_sku in ({$saihesku}) order by field(spd.saihe_sku,{$saihesku})";
// 		}

// 		if (!empty($data['order_source_sku'])) {
// 			//库存sku搜索
// 			$order_source_sku=explode(",",$data['order_source_sku']);
// 			$str = '';
// 			foreach ($order_source_sku as $k=>$v){
// 				$str .= " spd.order_source_sku like "."'%{$v}%' or";

// 			}
// 			$newStr = substr($str,0,strlen($str)-2);
// 			$where.=" and {$newStr}";
// 		}
// 	}
// 	if(!stripos($where,'order by')){
// 		$where.=" order by spd.client_sku asc";
// 	}

// 	$sql = "SELECT
// 			p.sellersku,
// 			p.asin,
// 			spd.saihe_sku,
// 			spd.client_sku,
// 			p.fnsku,
// 			spd.order_source_name,
// 			p.small_image AS small_image_url,
// 			p.title AS product_name,
// 			p.color,
// 			p.size,
// 			p.brand AS brand_name,
// 			sp.product_name_cn,
// 			sp.color AS saihe_color,
// 			sp.size AS saihe_size,
// 			sp.product_name AS saihe_product_name,
// 			s.shop_code,
// 			sp.product_group_sku
// 		FROM
// 			product_detail p
// 		LEFT JOIN saihe_product_detail spd ON p.sellersku = spd.order_source_sku
// 		LEFT JOIN saihe_product sp ON sp.sku = spd.saihe_sku
// 		LEFT JOIN shop s ON s.Id = p.shop_id
// 		WHERE
// 			$where";
// 	$list = json_decode(json_encode(DB::select($sql)), true);

// 	////处理数据
// 	foreach ($list as $ka => $va) {

// 		$productName = '';
// 		if (strlen($va['product_name'])) {
// 			$productName = mb_substr($va['product_name'],0,21)."...".mb_substr($va['product_name'],-21);
// 		} elseif (strlen($va['saihe_product_name'])) {
// 			$productName = mb_substr($va['saihe_product_name'],0,21)."...".mb_substr($va['saihe_product_name'],-21);
// 		}



// 		$list[$ka]['sku']  =  $va['sellersku']??'';
// 		$list[$ka]['client_sku'] = $va['client_sku']??'';
// 		$list[$ka]['spu'] = '';
// 		//新查询
// 		$skures = DB::table('self_sku')->where('sku', $va['sellersku'])->orwhere('old_sku',$va['sellersku'])->first();
// 		if($skures){
// 			$list[$ka]['sku'] = $skures->old_sku??$skures->sku;
// 			$customres = DB::table('self_custom_sku')->where('custom_sku',$skures->custom_sku)->orwhere('old_custom_sku',$skures->custom_sku)->first();
// 			$customres = json_decode(json_encode($customres),true);
// 			$list[$ka]['client_sku'] = $customres['old_custom_sku']??$customres['custom_sku'];
// 			if(!$va['product_name_cn']){
// 				$list[$ka]['product_name_cn'] = $customres['name'];
// 			 }
// 			$spures =  DB::table('self_spu')->where('spu', $skures->spu)->orwhere('old_spu',$skures->spu)->first();

// 			if($spures){
// 				$list[$ka]['spu'] = $spures->old_spu??$spures->spu;
// 			}
			

// 		}



	   
// 		$list[$ka]['contract_no'] = '';
// 		$list[$ka]['small_image_url'] = $va['small_image_url'];
// 		$list[$ka]['item_number'] = '';
	   
// //            $list[$ka]['sku'] = $va['goods_sku'];
// 		// $list[$ka]['sku'] = $va['sellersku'];

// 		$list[$ka]['product_name'] = $productName;
// 		$list[$ka]['color_cn'] = '';


// 		if(isset($customres)){
// 			$self_color = DB::table('self_color_size')->where('identifying',$customres['color'])->select('english_name','name')->first();
// 			$self_color =json_decode(json_encode($self_color),true);
// 			if($self_color){
// 				$list[$ka]['color_en'] = $self_color['english_name'].' '.$customres['size'];
// 				$list[$ka]['color_english'] =  $self_color['english_name'];
// 				$list[$ka]['color_name'] =  $self_color['name'];
// 			}
// 		}else{
// 			$list[$ka]['color_en'] = (strlen($va['color']) ? $va['color'] : $va['saihe_color']) . ' ' . (strlen($va['size']) ? $va['size'] : $va['saihe_size']);
// 		}

// 		$list[$ka]['size'] = $customres['size'];
// 		$list[$ka]['order_source_name'] = $va['order_source_name'];
// 		$list[$ka]['style_category'] = 'NEW';
// 		$list[$ka]['place'] = 'MADE IN CHINA';
// 		$list[$ka]['order_count'] = '';
// 		$list[$ka]['code_data'] = $va['fnsku'];
// 		$list[$ka]['shop_code'] = $va['shop_code'];
// 		$list[$ka]['diaopai'] = '';
// 		$list[$ka]['count'] = '';
// 		$list[$ka]['url'] = 'http://api.zity.cn/barcode/index.php?code='.$list[$ka]['client_sku'];
// 		// if($url_type=="custom_sku"){
// 		// 	$list[$ka]['url'] = 'http://8.134.97.20:9998/admin/SkuCodeImg.php?sku='.$list[$ka]['client_sku'];
// 		// }else{
// 		// 	$list[$ka]['url'] = 'http://8.134.97.20:9998/admin/CodeImg.php?fnsku='.$va['fnsku'];
// 		// }
		
// 	}

		$list = array();
	foreach ($lists as $key => $value) {
		# code...
		if($value->old_spu){
			$list[$key]['spu'] = $value->old_spu;
		}else{
			$list[$key]['spu'] =$value->spu;
		}
		
		$list[$key]['product_name_cn']  = $value->scname;
		$list[$key]['color_name']  =  $value->color_name;
		$list[$key]['color_english']  = $value->english_name;
		$list[$key]['size']  = $value->size;
		if($value->old_custom_sku){
			$custom_sku = $value->custom_sku;
		}else{
			$custom_sku = $value->custom_sku;
		}
		
		$list[$key]['url']  =  'http://api.zity.cn/barcode/index.php?code='.$custom_sku;
		$list[$key]['custom_sku'] = $custom_sku;
	}

//		return $list;
	$title = array(
		// 'shop_code' => '店铺代码',
		// 'sku' => '渠道sku',
		'spu' => '款号',
		// 'client_sku' => '库存SKU',
		'product_name_cn' => '中文名',
		'color_name' => '中文颜色',
		'color_english' => '英文颜色',
	   'size' => '尺码',
	   'custom_sku'=>'库存sku',
		// 'product_name' => '英文描述',
		// 'code_data' => 'fnsku',
		// 'diaopai' => '吊牌',
		// 'count' => '数量',
		'url' => 'url',
//            'order_count' => '数量',
	);

	error_reporting(E_ALL);
	date_default_timezone_set('PRC');
	$objPHPExcel = new \PHPExcel();
	$PHPExcel_Style_Alignment = new \PHPExcel_Style_Alignment;

	/*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
	$cellName = array('A', 'B', 'C', 'D', 'E','F','G');
	// 设置excel标题

	// 设置excel标题
	$index = 0;
	foreach ($title as $k => $v) {
		$objPHPExcel->getActiveSheet()->getStyle('A1:AA1')->getFont()->setBold(true);//第一行是否加粗
		$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(25);    //第一行行高
		$objPHPExcel->getActiveSheet()->setCellValue($cellName[$index] . "1", $v);
//            $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(60);
		$width = 20;
		if ($k == 'product_name') {
			$width = 50;
		}

		$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth($width);
		//设置水平居中
		$objPHPExcel->getActiveSheet()
			->getStyle('A1:AA1')
			->getAlignment()
			->setHorizontal($PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		//设置垂直居中
		$objPHPExcel->getActiveSheet()
			->getStyle('A1:AA1')
			->getAlignment()
			->setVertical($PHPExcel_Style_Alignment::VERTICAL_CENTER);
		//自动换行
		$objPHPExcel->getActiveSheet()
			->getStyle('A1:AA1')
			->getAlignment()
			->setWrapText(true);

		$index++;
	}

	//判断文件夹是否已存在
	$wenjian = 'assess/Qiniu';
	if (!is_dir($wenjian)) {
		mkdir($wenjian, 0777, true);
	}
	// 填充excel数据 与标题一一对应
	$img_del = array();//需删除的图片
	foreach ($list as $k => $v) {
		$num = $k + 2;
		//字体大小
		$objPHPExcel->getActiveSheet()
			->getStyle('A' . $num . ':' . 'AA' . $num)
			->getFont()
			->setSize(10);
		//设置水平居中
		$objPHPExcel->getActiveSheet()
			->getStyle('A' . $num . ':' . 'AA' . $num)
			->getAlignment()
			->setHorizontal($PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		//设置垂直居中
		$objPHPExcel->getActiveSheet()
			->getStyle('A' . $num . ':' . 'AA' . $num)
			->getAlignment()
			->setVertical($PHPExcel_Style_Alignment::VERTICAL_CENTER);
		//自动换行
		$objPHPExcel->getActiveSheet()
			->getStyle('A' . $num . ':' . 'AA' . $num)
			->getAlignment()
			->setWrapText(true);

		// 重置列索引起始位
		$i = 0;
		foreach ($title as $key => $value) {
			$objPHPExcel->setActiveSheetIndex(0)//Excel的第A列，uid是你查出数组的键值，下面以此类推
			->setCellValue($cellName[$i] . $num, $v[$key]);
			$i++;
		}
	}


	$objPHPExcel->getActiveSheet()->setTitle('work');
	$objPHPExcel->setActiveSheetIndex(0);
	header('Content-Type: application/vnd.ms-excel');
	header('Content-Disposition:attachment;filename="条码列表.xls"');
	header('Cache-Control: max-age=1');
	$objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
	$objWriter->save('php://output');
	// //删除下载的图片

	// if(!empty($img_del)){
	// 	foreach ($img_del as $val){
	// 		unlink($val);
	// 	}
	// }

	exit();
}


    public function barcode_export($data){
        $where = "1=1";

		$url_type = $data['url_type']??'custom_sku';
        if (!empty($data['id'])) {
            $idString = '';
            $idData = explode(',',$data['id']);
            foreach($idData as $idVal){
                $idStr  = "'".$idVal."',";
                $idString .= $idStr;
            }
            $newId = substr($idString,0,strlen($idString)-1);
            // sku_ids sku id
            $where .= " and p.id in ({$newId}) GROUP BY p.sellersku order by field(p.id,{$newId})";
        } else {
            if (!empty($data['platform_id'])) {
                //     $where .= " and p.platform_id = {$params['platform_id']}";
                $where .= " and p.platform_id = {$data['platform_id']}";
            }
            if (!empty($data['shop_id'])) {
                $where .= " and p.shop_id = {$data['shop_id']}";
            }
            if (!empty($data['product_sku'])) {
                $where .= " and p.sellersku like '%{$data['product_sku']}%'";
            }
            if(!empty($data['sellersku_arr'])){
                $where .= " and p.sellersku in ({$data['sellersku_arr']}) order by field(p.sellersku,{$data['sellersku_arr']})";
            }
            if (!empty($data['product_fnsku'])) {
                $where .= " and p.fnsku like '%{$data['product_fnsku']}%'";
            }
            if (!empty($data['product_asin'])) {
                $where .= " and p.asin like '%{$data['product_asin']}%'";
            }
            if (!empty($data['product_key'])) {
                $product_key=$data['product_key'];
                $keySql = "select sku
                from saihe_product
                where product_name_cn like '%{$product_key}%'
                ";
                $key = json_decode(json_encode(DB::select($keySql)), true);
                $skulist=array();
                foreach ($key as $v){
                    $skulist[]="'".trim($v['sku'])."'";
                }
                if(isset($skulist)) $saihesku=implode(",",$skulist);

                $where .= " and spd.saihe_sku in ({$saihesku}) order by field(spd.saihe_sku,{$saihesku})";
            }

            if (!empty($data['order_source_sku'])) {
                //库存sku搜索
                $order_source_sku=explode(",",$data['order_source_sku']);
                $str = '';
                foreach ($order_source_sku as $k=>$v){
                    $str .= " spd.order_source_sku like "."'%{$v}%' or";

                }
                $newStr = substr($str,0,strlen($str)-2);
                $where.=" and {$newStr}";
            }
        }

        if(!stripos($where,'order by')){

			$where.=" GROUP BY p.sellersku";
            $where.=" order by spd.client_sku asc ";
        }

        $sql = "SELECT
                p.sellersku,
                p.asin,
                spd.saihe_sku,
                spd.client_sku,
                p.fnsku,
                spd.order_source_name,
                p.small_image AS small_image_url,
                p.title AS product_name,
                p.brand AS brand_name,
                sp.product_name_cn,
                sp.color AS saihe_color,
                sp.size AS saihe_size,
                sp.product_name AS saihe_product_name,
                s.identifying,
                sp.product_group_sku,
                scs.name AS custom_sku_name
            FROM
                product_detail p
            LEFT JOIN saihe_product_detail spd ON p.sellersku = spd.order_source_sku
            LEFT JOIN saihe_product sp ON sp.sku = spd.saihe_sku
            LEFT JOIN shop s ON s.Id = p.shop_id
            LEFT JOIN self_custom_sku scs ON p.custom_sku_id = scs.id
            WHERE
                $where";

        $list = json_decode(json_encode(DB::select($sql)), true);

		// var_dump($list);
		// return;

        ////处理数据
        foreach ($list as $ka => $va) {

            $productName = '';
            if (strlen($va['product_name'])) {
                $productName = mb_substr($va['product_name'],0,21)."...".mb_substr($va['product_name'],-21);
            } elseif (strlen($va['saihe_product_name'])) {
                $productName = mb_substr($va['saihe_product_name'],0,21)."...".mb_substr($va['saihe_product_name'],-21);
            }

			// $list[$ka]['sku']  =  $va['sellersku']??'';
			$list[$ka]['client_sku'] = $va['client_sku']??'';
			$list[$ka]['spu'] = '';

			$list[$ka]['color_en'] = '';
			$list[$ka]['size'] = '';
            //新查询
            $skures = DB::table('self_sku')->where('sku', $va['sellersku'])->orwhere('old_sku',$va['sellersku'])->first();
            if($skures){
				$list[$ka]['sku'] = $skures->sku;
				if($skures->old_sku){
					$list[$ka]['sku'] = $skures->old_sku;
				}
                $customres = DB::table('self_custom_sku')->where('id',$skures->custom_sku_id)->first();
                $customres = json_decode(json_encode($customres),true);
				$list[$ka]['client_sku'] = empty($customres['old_custom_sku']) ? $customres['custom_sku'] : $customres['old_custom_sku'];
				if($customres['color']){
					$colors = DB::table('self_color_size')->where('identifying',$customres['color'])->first();
					if($colors){
						$list[$ka]['color_en'] =  $colors->english_name.'/'.$customres['size'];
					}
				}
				
				$list[$ka]['size'] =   $customres['size'];
//                if(!$va['product_name_cn']){
//                    $list[$ka]['product_name_cn'] = $customres['name'];
//                 }
                $list[$ka]['product_name_cn'] = $va['custom_sku_name']??'';
				$spures =  DB::table('self_spu')->where('id', $skures->spu_id)->first();

				if($spures){
					if($spures->old_spu){
						$list[$ka]['spu'] = $spures->old_spu;
					}else{
						$list[$ka]['spu'] = $spures->spu;
					}
					
				}
				

            }



           
            $list[$ka]['contract_no'] = '';
            $list[$ka]['small_image_url'] = $va['small_image_url'];
            $list[$ka]['item_number'] = '';
           
//            $list[$ka]['sku'] = $va['goods_sku'];
            // $list[$ka]['sku'] = $va['sellersku'];

            $list[$ka]['product_name'] = $productName;
            $list[$ka]['color_cn'] = '';


//            if(isset($customres)){
//                $self_color = DB::table('self_color_size')->where('identifying',$customres['color'])->select('english_name')->first();
//                $self_color =json_decode(json_encode($self_color),true);
//                if($self_color){
//                    $list[$ka]['color_en'] = $self_color['english_name'].' '.$customres['size'];
//                }
//            }else{
//                $list[$ka]['color_en'] = (strlen($va['color']) ? $va['color'] : $va['saihe_color']) . ' ' . (strlen($va['size']) ? $va['size'] : $va['saihe_size']);
//            }
//
//            $list[$ka]['size'] = $va['size'];
            $list[$ka]['order_source_name'] = $va['order_source_name'];
            $list[$ka]['style_category'] = 'NEW';
            $list[$ka]['place'] = 'MADE IN CHINA';
            $list[$ka]['order_count'] = '';
            $list[$ka]['code_data'] = $va['fnsku'];
            $list[$ka]['shop_code'] = $va['identifying'];
            $list[$ka]['diaopai'] = '';
            $list[$ka]['count'] = '';
			if($url_type=="custom_sku"){
				$list[$ka]['url'] = 'http://api.zity.cn/barcode/index.php?code='.$list[$ka]['client_sku'];
			}else{
				$list[$ka]['url'] = 'http://8.134.97.20:9998/admin/CodeImg.php?fnsku='.$va['fnsku'];
			}
			
        }
		// var_dump($list);
		// return;
//		return $list;
        $title = array(
            'shop_code' => '店铺代码',
            'sku' => '渠道sku',
            'spu' => '款号',
            'client_sku' => '库存SKU',
            'product_name_cn' => '中文名',
            'color_en' => '颜色/码数',
			'asin'=>'asin',
           // 'size' => '尺码',
            'product_name' => '英文描述',
            'code_data' => 'fnsku',
            'diaopai' => '吊牌',
            'count' => '数量',
			'url' => 'url',
//            'order_count' => '数量',
        );

        error_reporting(E_ALL);
        date_default_timezone_set('PRC');
        $objPHPExcel = new \PHPExcel();
        $PHPExcel_Style_Alignment = new \PHPExcel_Style_Alignment;

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
        $cellName = array('A', 'B', 'C', 'D', 'E','F','G','H','I','J','K','L');
        // 设置excel标题

        // 设置excel标题
        $index = 0;
        foreach ($title as $k => $v) {
            $objPHPExcel->getActiveSheet()->getStyle('A1:AA1')->getFont()->setBold(true);//第一行是否加粗
            $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(25);    //第一行行高
            $objPHPExcel->getActiveSheet()->setCellValue($cellName[$index] . "1", $v);
//            $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(60);
            $width = 20;
            if ($k == 'product_name') {
                $width = 50;
            }

            $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth($width);
            //设置水平居中
            $objPHPExcel->getActiveSheet()
                ->getStyle('A1:AA1')
                ->getAlignment()
                ->setHorizontal($PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //设置垂直居中
            $objPHPExcel->getActiveSheet()
                ->getStyle('A1:AA1')
                ->getAlignment()
                ->setVertical($PHPExcel_Style_Alignment::VERTICAL_CENTER);
            //自动换行
            $objPHPExcel->getActiveSheet()
                ->getStyle('A1:AA1')
                ->getAlignment()
                ->setWrapText(true);

            $index++;
        }

        //判断文件夹是否已存在
        $wenjian = 'assess/Qiniu';
        if (!is_dir($wenjian)) {
            mkdir($wenjian, 0777, true);
        }
        // 填充excel数据 与标题一一对应
        $img_del = array();//需删除的图片
        foreach ($list as $k => $v) {
            $num = $k + 2;
            //字体大小
            $objPHPExcel->getActiveSheet()
                ->getStyle('A' . $num . ':' . 'AA' . $num)
                ->getFont()
                ->setSize(10);
            //设置水平居中
            $objPHPExcel->getActiveSheet()
                ->getStyle('A' . $num . ':' . 'AA' . $num)
                ->getAlignment()
                ->setHorizontal($PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //设置垂直居中
            $objPHPExcel->getActiveSheet()
                ->getStyle('A' . $num . ':' . 'AA' . $num)
                ->getAlignment()
                ->setVertical($PHPExcel_Style_Alignment::VERTICAL_CENTER);
            //自动换行
            $objPHPExcel->getActiveSheet()
                ->getStyle('A' . $num . ':' . 'AA' . $num)
                ->getAlignment()
                ->setWrapText(true);

            // 重置列索引起始位
            $i = 0;
            foreach ($title as $key => $value) {
                $objPHPExcel->setActiveSheetIndex(0)//Excel的第A列，uid是你查出数组的键值，下面以此类推
                ->setCellValue($cellName[$i] . $num, $v[$key]);
                $i++;
            }
        }


        $objPHPExcel->getActiveSheet()->setTitle('work');
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename="条码列表.xls"');
        header('Cache-Control: max-age=1');
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter->save('php://output');
        //删除下载的图片

        if(!empty($img_del)){
            foreach ($img_del as $val){
                unlink($val);
            }
        }

        exit();
    }

	

    public function product_excel_export($data){
        ////获取Excel文件数据
        //载入文档
        $objPHPExcelReader = \PHPExcel_IOFactory::load($data['file']['tmp_name']);
        $currentSheet = $objPHPExcelReader->getSheet(0);//读取第一个工作表(编号从 0 开始)
//		$allColumn = 'O';//取得总列数
        $allColumn = $currentSheet->getHighestColumn();//取得总列数
        $allRow = $currentSheet->getHighestRow();//取得总行数
        $add_list = array();
		$err_sku = [];
        /**从第1行开始输出*/
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            /**从第A列开始输出*/
            for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
                $key = $currentSheet->getCellByColumnAndRow((ord($currentColumn) - 65), 1)->getValue();//数据键值
                $val = $currentSheet->getCellByColumnAndRow((ord($currentColumn) - 65), $currentRow)->getValue();//数据
                $gva = $currentSheet->getCellByColumnAndRow((ord($currentColumn) - 65), $currentRow)->getFormattedValue();//数据

                if ($currentColumn == 'G') {
                    break;
                }
                //判断键名是否正确
                $array_key = array('渠道sku');
                if (!in_array($key, $array_key)) {
					return 'Excel数据格式不对,请清除多余格式，或下载Excel模板进行导入';
                }

                if ($key == '渠道sku') {
                    $add_list[$currentRow - 2]['sellersku'] = $val;
					$skus = DB::table('self_sku')->where('sku',$val)->orwhere('old_sku',$val)->first();
					if(!$skus){
						$err_sku[] = $val;
					}
                }
            }
        }
//        var_dump($add_list);die;
        // 处理数据
       // $list = array();

        //// 存储数据
		if(count($err_sku)>0){
			return '以下sku未录入'.json_encode($err_sku);
		}

        if (empty($add_list)) {
			return 'Excel文件数据为空';
        }
        //将数组拆分成带引号的字符串
        $sku_arr = array_column($add_list,'sellersku');
        $limit = count($sku_arr);
        $sku = implode(',', array_map(
                function ($str) {
                    return sprintf("'%s'", $str);
                }, $sku_arr
            )
        );
        $params['limit'] = $limit;
        $params['sellersku_arr'] = $sku_arr;
		// var_dump( $params);
        $product_model = new \App\Models\ProductModel();
        $list = $product_model->getBarcode($params);
        return $list;



    }


    //亚马逊导入新品
    public function new_product_export($data){

    }




}//类结束符
